package com.greate.community.event;

import com.greate.community.util.CommunityConstant;
import org.apache.kafka.clients.admin.AdminClient;
import org.apache.kafka.clients.admin.NewTopic;
import org.apache.kafka.common.errors.TopicExistsException;
import java.util.Collections;
import java.util.Properties;

public class KafkaTopicCreator implements CommunityConstant {
    public static void main(String[] args) {
        // Kafka 配置
        Properties props = new Properties();
        props.put("bootstrap.servers", "localhost:9092"); // Kafka broker 地址
        props.put("key.deserializer", "org.apache.kafka.common.serialization.StringDeserializer");
        props.put("value.deserializer", "org.apache.kafka.common.serialization.StringDeserializer");

        // 创建 AdminClient 实例
        try (AdminClient adminClient = AdminClient.create(props)) {

            // 创建新主题 // 3个分区，2个副本
            NewTopic commentTopic = new NewTopic(TOPIC_COMMNET, 3, (short) 2);
            NewTopic likeTopic = new NewTopic(TOPIC_LIKE, 3, (short) 2);
            NewTopic followTopic = new NewTopic(TOPIC_FOLLOW, 3, (short) 2);
            NewTopic publishTopic = new NewTopic(TOPIC_PUBLISH, 3, (short) 2);
            NewTopic deleteTopic = new NewTopic(TOPIC_DELETE, 3, (short) 2);

            // 将主题加入列表
            try {
                adminClient.createTopics(
                        Collections.singletonList(commentTopic)
                ).all().get();
                adminClient.createTopics(
                        Collections.singletonList(likeTopic)
                ).all().get();
                adminClient.createTopics(
                        Collections.singletonList(followTopic)
                ).all().get();
                adminClient.createTopics(
                        Collections.singletonList(publishTopic)
                ).all().get();
                adminClient.createTopics(
                        Collections.singletonList(deleteTopic)
                ).all().get();
                System.out.println("Topics created successfully!");
            } catch (TopicExistsException e) {
                System.out.println("Topic already exists.");
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
}
